import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-01-18
 * Time: 22:34
 */
public class test1 {
    /*
    LeetCode 15 三数之和
     */
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        // 排序
        Arrays.sort(nums);
        // 左右指针
        int n= nums.length;
        for(int i=0;i<n;){
            if(nums[i]>0){
                break;
            }
            int left = i+1;
            int right = n-1;
            int target = -nums[i];
            while(left<right){
                if(nums[left]+nums[right]<target){
                    left++;
                }else if(nums[left]+nums[right]>target){
                    right--;
                }else{
                    ret.add(new ArrayList<Integer>(Arrays.asList(nums[i],nums[left],nums[right])));
                    left++;
                    right--;
                    // 去重
                    while(left<right && nums[left]==nums[left-1]){
                        left++;
                    }
                    while(left<right && nums[right]==nums[right+1]){
                        right--;
                    }
                }
            }
            i++;
            // 去重
            while(i<n && nums[i]==nums[i-1]){
                i++;
            }
        }
        return ret;
    }
}
